package com.CST.interceptor;


import cn.hutool.core.date.DateUtil;
import com.CST.common.constant.TokenConstant;
import com.CST.config.JwtConfig;
import io.swagger.models.HttpMethod;
import org.springframework.messaging.handler.HandlerMethod;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @Author cc
 * @Date 2020/6/28 17:41
 * @Version 1.0 Token拦截器
 */
@Component
public class TokenInterceptor extends HandlerInterceptorAdapter {

    @Resource
    private JwtConfig jwtConfig;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
				     Object handler) throws Exception {
	  //地址过滤
	  String uri = request.getRequestURI();
	  // 如果不是映射到方法直接通过
	  if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
		return true;
	  }
	  //去除不需要校验的接口名
	  if (uri.contains("/login") || uri.contains("/token") || uri.contains("/error") || uri
		.contains("/error") || uri.contains("app") || uri.contains("Excel") || uri.contains("/bdSysUser")
			  || uri.contains("/swagger-ui.html")
	  ) {
		//if (!uri.contains("/login1")){
		return true;
	  }
	  // Token 验证
//	  String token = request.getHeader(jwtConfig.getHeader());
//	  if (StringUtils.isEmpty(token)) {
//		token = request.getParameter(jwtConfig.getHeader());
//	  }
//	  if (StringUtils.isEmpty(token)) {
//		throw new Exception(jwtConfig.getHeader() + "不能为空");
//	  }
//	  Map<String, Object> claims = jwtConfig.getTokenClaim(token);
//	  if (null == claims || jwtConfig.isTokenExpired(
//		DateUtil.date(Long.parseLong(claims.get(TokenConstant.EXP).toString()) * 1000L))) {
//		throw new Exception(jwtConfig.getHeader() + "失效，请重新登录");
//	  }
	  return true;
    }
}
